package com.qkl.user.utils;

import com.qkl.user.config.JwtConfig;

import com.qkl.user.model.LoginUser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
@Slf4j
@Component
public class JwtUtils {
    @Autowired
    private  JwtConfig jwtConfig;
    // 生成JWT令牌
    public  String generateJwtToken(Authentication authentication) {
        LoginUser userPrincipal =
                (LoginUser) authentication.getPrincipal();
        Key signingKey = Keys.hmacShaKeyFor(jwtConfig.getSecret().getBytes(StandardCharsets.UTF_8));

        return Jwts.builder()
                .setSubject(userPrincipal.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date((new Date()).getTime() + jwtConfig.getExpiration()))
                .signWith(signingKey)
                .compact();
    }

    public static Long getUserId(){
        LoginUser userDetails =  (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return userDetails.getId();
    }
}
